<?php

namespace App\Modules\Admin\Services\Water\Member;

use App\Exceptions\Exception;
use App\Modules\Admin\Entities\Member\UserScoreModel;
use App\Modules\Admin\Entities\Member\UsersModel;
use App\Modules\Admin\Entities\Water\GiftScoreModel;
use App\Modules\Admin\Services\BaseService;
use Illuminate\Support\Facades\DB;

class GiftScoreService extends BaseService
{
    public function __construct(GiftScoreModel $model)
    {
        $this->model = $model;
        $this->userScoreModel = new UserScoreModel();
        $this->userModel = new UsersModel();
        $this->with=['community'];
    }
    public function lists(array $params) : array
    {
        $params['where_callback'] = function($query) use ($params){
            $request = request();
            // 按照名称进行搜索
            if (!empty($search = $request->input('search', ''))){
                $query->where('nickname', 'LIKE', '%' . trim($search) . '%');
            }
            if (!empty($search = $request->input('search', ''))){
                $query->where('nickname', 'LIKE', '%' . trim($search) . '%');
            }
        };
        return parent::lists($params); // TODO: Change the autogenerated stub
    }


    public function create(array $params)
    {
        $communityId = $params['community_id'];
        $score = $params['score'];
        $user_id = $params['user_id'];
        $proportion = $params['proportion'];
        $gift_time = $params['end_signed'];
        $waterMachineData = $params['waterMachineData'];

        $gift_info = $this->model->where(['community_id'=>$communityId,'gift_time'=>strtotime($gift_time)])->first();
        if ($gift_info){
            $this->error = '当前日期：'.$gift_time.',已赠送积分，禁止重复赠送';
            return false;
        }
        DB::beginTransaction();
        try{
            $detail = parent::create([
                'month'=>date('Y-m-d',strtotime($gift_time)),
                'gift_time'=>strtotime($gift_time),
                'score'=>$score,
                'proportion'=>$proportion/100,
                'community_id'=>$communityId,
                'score_proportion'=>$params['score_proportion'],
                'spread_uid'=>$params['spread_uid'],
                'manage_ratio'=>$params['manage_ratio']??0,
                'manage_score'=>$params['manage_score']??0,
                'user_id'=>$user_id,
            ]); // TODO: Change the autogenerated stub

            $bool = $this->distributeUsersScore($params,$detail);

            if ($params['spread_uid']){

                $detail_spread = parent::create([
                    'month'=>date('Y-m-d',strtotime($gift_time)),
                    'title'=>'管理积分',
                    'gift_time'=>strtotime($gift_time),
                    'score'=>$score,
                    'proportion'=>$params['manage_ratio']/100,
                    'community_id'=>$communityId,
                    'score_proportion'=>$params['manage_score'],
                    'spread_uid'=>$params['spread_uid'],
                    'manage_ratio'=>0,
                    'manage_score'=>0,
                    'user_id'=>$params['spread_uid'],
                ]); // TODO: Change the autogenerated stub

                $bool = $this->distributeUsersSpreadScore($params,$detail_spread);
            }
            if (!$bool) {
                DB::rollBack();
                $this->error = '分发积分出错';
                return false;
            }
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }
    public function distributeUsersScore($params,$detail){
        $user_id = $params['user_id'];
        $gift_time = $params['end_signed'];
        $waterMachineData = $params['waterMachineData'];
        foreach ($waterMachineData as $value=>&$item){
            $item['user_id'] = $user_id;
            $score = $item['score'];
            $user = $this->userModel->getUserInfo($user_id,'integral');
            $userScoreCreate = [
                'title' => '增加积分',
                'gift_id'=>$detail['id'],
                'month'=>date('Y-m-d',strtotime($gift_time)),
                'water_id'=>$item['water_id'],
                'score'=>$score,
                'balance' => bcadd($user['integral'] ,$score,3),
                'proportion'=> $detail['proportion'],
                'sum_score'=>$item['sum_score'],
                'spread_uid'=>$item['spread_uid'],
                'manage_ratio'=>$item['manage_ratio']??0,
                'manage_score'=>$item['manage_score']??0,
                'user_id'=>$user_id,
                'type' => $item['water_role'],
                'gift_time'=>strtotime($gift_time),
            ];
            UserScoreModel::create($userScoreCreate);
            $this->userModel->scoreIncrement($user_id,$score);
            \App\Modules\Admin\Entities\Log\UserScoreLogModel::getInstance()->setScoreLogCreate(1,$userScoreCreate);
        }
        return true;
    }

    public function distributeUsersSpreadScore($params,$detail){
        $user_id = $params['spread_uid'];
        $gift_time = $params['end_signed'];
        $waterMachineData = $params['waterMachineData'];
        foreach ($waterMachineData as $value=>&$item){
            $item['user_id'] = $user_id;
            $score = $item['manage_score'];
            $user = $this->userModel->getUserInfo($user_id,'integral');
            $userScoreCreate = [
                'title' => '管理积分',
                'gift_id'=>$detail['id'],
                'month'=>date('Y-m-d',strtotime($gift_time)),
                'water_id'=>$item['water_id'],
                'score'=>$score,
                'balance' => bcadd($user['integral'] ,$score,3),
                'proportion'=> $detail['manage_ratio'],
                'sum_score'=>$item['sum_score'],
                'spread_uid'=>$item['spread_uid'],
                'manage_ratio'=>0,
                'manage_score'=>0,
                'user_id'=>$user_id,
                'type' => $item['water_role'],
                'gift_time'=>strtotime($gift_time),
            ];
            UserScoreModel::create($userScoreCreate);
            $this->userModel->scoreIncrement($user_id,$score);
            \App\Modules\Admin\Entities\Log\UserScoreLogModel::getInstance()->setScoreLogCreate(1,$userScoreCreate);
        }
        return true;
    }



}
